/**
 * This class is used to scrape the news content from a mustangs website and
 * display it to the user.
 * @author Chirag Mistry
 */

package ca.uwo.android.rss;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.util.Linkify;
import android.widget.TextView;
import ca.uwo.android.BaseMenuActivity;
import ca.uwo.android.R;

public class WebScraper  extends BaseMenuActivity{

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scrapedcontent);
		
		//get the url and text veiw where the content will be displayed
		String url = this.getIntent().getExtras().getString("URL");
		TextView showMustangContent = (TextView)findViewById(R.id.scrapedtext);

		//get and parse html data for the news headline from the mustang website
		String content = getHTMLContent(url);
		Spanned scrapedContent = scrapeContent(content, "<div class=\"story_content\">", "</div>");
		showMustangContent.append(scrapedContent);	//display data
		
		//linkify the text (i.e. phone numbers, websites, etc.)
		Linkify.addLinks(showMustangContent, Linkify.ALL);
	}

	/**
	 * This method is used to read the HTML source from the news item 
	 * on the mustang website and store it locally as a string
	 * @param url	url to retrieve headline content
	 * @return	String	- contains the HTML source of the headline
	 */
	private String getHTMLContent(String url) {
		StringBuilder newsContent = new StringBuilder();
		String response = "";
		DefaultHttpClient client = new DefaultHttpClient();
		
		try{
			//open a connection to url and retrieve data
			URI uri = new URI(url);
			HttpGet method = new HttpGet(uri);
			HttpResponse res = client.execute(method);
			InputStream data = res.getEntity().getContent();

			//create a string from data retrieved
			BufferedReader reader = new BufferedReader(new InputStreamReader(
			data), 8);
			while ((response = reader.readLine()) != null) {
				newsContent.append(response);
			}
		}catch(Exception e){
			
			//create empty alert dialog
			AlertDialog alert = new AlertDialog.Builder(WebScraper.this)
			.setTitle("Error")
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		                finish();	//close the current activity and return to the previous one
		            }
		        })
	        .create();
		
			//Error checking
			if(e instanceof URISyntaxException){
				alert.setMessage("The URL for the Mustang News headline is invalid!");
			}
			else if(e instanceof ClientProtocolException){
				alert.setMessage("The content for this headline could not be retrieved!");
			}
			else if(e instanceof IOException){
				alert.setMessage("Could not read the content returned from website!");
			}
			else{
				alert.setMessage("There was a problem while retrieving the content for this headline");
			}
			
			alert.show();	//show populated alert dialog based on error type
		}
		
		return newsContent.toString();
	}
	
	/**
	 * This method is used to find and filter the content between two Html tags
	 * @param content	The string content that is to be searched
	 * @param startTag	The opening Html tag to look for
	 * @param endTag	The closing Html tag to look for
	 * @return result	- The content contained between the opening and closing tags
	 */
	private Spanned scrapeContent(String content, String startTag, String endTag) {
		int start = content.indexOf(startTag) + startTag.length() + 2;
		int end = content.indexOf(endTag, start);

		Spanned result = Html.fromHtml(content.substring(start, end));
		return result;
	}

}
